<template>
	<el-card class="box-card" v-loading="loading">
		<template #header>
			<div class="title">
				<el-icon v-if="completed" class="icon" color="#67C23A"><SuccessFilled /></el-icon>

				{{ `${completed ? '您已完成' : ''}实名认证` }}
			</div>
		</template>
		<!-- 未完成实名认证 -->
		<template v-if="!completed">
			<div class="tip">
				<el-icon class="el-icon"><InfoFilled /></el-icon>
				完成实名认证后才能添加就诊人，正常进行挂号，为了不影响后续步骤，建议提前实名认证。
			</div>
			<div class="form_box">
				<el-form style="width: 665px" label-width="80px" :model="formData" :rules="rules" ref="ruleFormRef">
					<el-form-item label="用户姓名" prop="name">
						<el-input placeholder="请输入用户姓名" clearable v-model="formData.name" />
					</el-form-item>
					<el-form-item label="证件类型" prop="certificatesType">
						<el-select placeholder="请选择证件类型" clearable v-model="formData.certificatesType">
							<el-option
								v-for="item in certationType"
								:key="item.id"
								:label="item.name"
								:value="item.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="证件号码" prop="certificatesNo">
						<el-input placeholder="请输入证件号码" clearable v-model="formData.certificatesNo" />
					</el-form-item>
					<el-form-item label="上传证件" prop="certificatesUrl">
						<el-upload
							ref="uploadRef"
							list-type="picture-card"
							:limit="1"
							:on-exceed="onExceed"
							:on-success="onSuccess"
							:on-preview="onPreview"
							:on-remove="onRemove"
							:action="baseURL + '/oss/file/fileUpload?fileHost=userAuah'">
							<img class="upload_img" src="../../../assets/images/auth_example.png" alt="" />
						</el-upload>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="submit">提交</el-button>
						<el-button @click="reset">重写</el-button>
					</el-form-item>
				</el-form>
			</div>
		</template>
		<!-- 已完成实名认证 -->
		<template v-else>
			<el-descriptions :column="1" border>
				<el-descriptions-item label="用户姓名">{{ userInfo?.name }}</el-descriptions-item>
				<el-descriptions-item label="证件类型">
					{{ userInfo?.certificatesType === '10' ? '身份证' : '户口本' }}
				</el-descriptions-item>
				<el-descriptions-item label="证件号码">{{ userInfo?.certificatesNo }}</el-descriptions-item>
			</el-descriptions>
		</template>

		<el-dialog v-model="dialogVisible">
			<el-image style="width: 100%; height: 100%" :src="dialogImageUrl" fit="contain" />
		</el-dialog>
	</el-card>
</template>

<script setup lang="ts">
import { InfoFilled, SuccessFilled } from '@element-plus/icons-vue';
import { ref, computed, reactive, watch } from 'vue';
import { getUserInfo, getCertationType, userCertation } from '@/api/user';
import { UserInfo, CertificatesType, UserCertationParams, ResponseData } from '@/api/user/type';
import { baseURL } from '@/utils/request';
import { ElMessage, UploadFile, UploadInstance, FormRules, FormInstance } from 'element-plus';

let userInfo = ref<UserInfo | undefined>();

let certationType = ref<CertificatesType[]>([]);

let loading = ref(true);

const ruleFormRef = ref<FormInstance>();

const formData = reactive<UserCertationParams>({
	certificatesNo: '',
	certificatesType: '',
	certificatesUrl: '',
	name: '',
});

const rules: FormRules = {
	name: {
		required: true,
		validator(_rule, value, callback) {
			if (!value) {
				callback('用户姓名不能为空');
			} else if (!/^[\u4e00-\u9fa5]{1,}$/.test(value)) {
				callback('用户姓名必须由中文组成');
			}

			callback();
		},
	},
	certificatesType: {
		required: true,
		message: '证件类型不能为空',
	},
	certificatesNo: {
		required: true,
		validator(_rule, value, callback) {
			if (formData.certificatesType) {
				if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value) || !/^(\d{17})(\d|X)$/.test(value)) {
					callback('验证不通过，请检查格式');
				} else {
					callback();
				}
			} else {
				callback('请先选择证件类型');
			}
		},
	},
	certificatesUrl: {
		required: true,
		message: '请上传证件',
	},
};

watch(
	() => formData.certificatesType,
	() => {
		if (formData.certificatesNo) {
			ruleFormRef.value?.validateField('certificatesNo');
		}
	}
);

let dialogVisible = ref(false);
let dialogImageUrl = ref('');

let uploadRef = ref<UploadInstance>();

// 获取用户信息
function getUserInfoFn() {
	loading.value = true;
	getUserInfo()
		.then((res) => {
			if (res.ok) {
				userInfo.value = res.data;
			}
		})
		.finally(() => {
			loading.value = false;
		});
}

// 获取实名认证的类型
function getCertationTypeFn() {
	getCertationType().then((res) => {
		if (res.ok) {
			certationType.value = res.data;
		}
	});
}

// 达到限制上传数量
function onExceed() {
	ElMessage.error('限制上传一张');
}

// 上传成功
function onSuccess(response: ResponseData) {
	formData.certificatesUrl = response.data;

	ruleFormRef.value?.clearValidate('certificatesUrl');
}

// 图片预览回调
function onPreview(file: UploadFile) {
	dialogImageUrl.value = file.url!;
	dialogVisible.value = true;
}

// 图片移除回调
function onRemove() {
	formData.certificatesUrl = '';
}

// 重写
function reset() {
	formData.certificatesNo = '';
	formData.certificatesType = '';
	formData.certificatesUrl = '';
	formData.name = '';

	uploadRef.value?.clearFiles();
}

// 提交
function submit() {
	ruleFormRef.value?.validate((boo) => {
		if (!boo) return;
		userCertation(formData).then(
			(res) => {
				if (res.ok) {
					getUserInfoFn();

					ElMessage.success('认证成功');
				} else {
					ElMessage.error(res.message);
				}
			},
			() => {
				ElMessage.error('认证失败');
			}
		);
	});
}

getUserInfoFn();
getCertationTypeFn();

// 是否完成实名认证
let completed = computed(() => {
	if (userInfo.value) {
		return userInfo.value.authStatus === 1;
	}
	return false;
});
</script>

<style scoped lang="scss">
.box-card {
	.title {
		display: flex;
		align-items: center;
		.icon {
			margin-right: 2px;
			font-size: 18px;
		}
	}
	.tip {
		display: flex;
		align-items: center;
		justify-content: center;
		color: #666;
		margin-bottom: 20px;
		.el-icon {
			margin-right: 2px;
		}
	}
	.form_box {
		display: flex;
		justify-content: center;
		.upload_img {
			width: 100%;
			border-radius: 4px;
		}
	}
}
</style>
